package com.ycy.topapi;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONObject;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.taobao.api.ApiException;
import com.taobao.api.Constants;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.PromotionInItem;
import com.taobao.api.domain.TaobaokeItem;
import com.taobao.api.domain.TaobaokeItemDetail;
import com.taobao.api.request.TaobaokeItemsDetailGetRequest;
import com.taobao.api.request.TaobaokeItemsGetRequest;
import com.taobao.api.request.UmpPromotionGetRequest;
import com.taobao.api.response.TaobaokeItemsDetailGetResponse;
import com.taobao.api.response.TaobaokeItemsGetResponse;
import com.taobao.api.response.UmpPromotionGetResponse;

public class TopApiUtil{
	private static Logger logger = LogManager.getLogger(TopApiUtil.class);
	
	private static String url;

	private static String appkey;

	private static String secret;

	private static TaobaoClient client;

	static {
		init();
	}

	private static void init(){
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream(TopApiUtil.class.getResource("/top.properties").getFile()));
		} catch (FileNotFoundException e) {
			logger.error(e.toString());
		} catch (IOException e) {
			logger.error(e.toString());
		}
		url = "0".equals(prop.getProperty("top.isTest")) ? prop.getProperty("top.apiUrl") : prop
				.getProperty("top.apiUrlTest");
		appkey = prop.getProperty("top.appkey");
		secret = prop.getProperty("top.secret");
		client = new DefaultTaobaoClient(url, appkey, secret, Constants.FORMAT_JSON);
	}

	public static TopResult tbkConvert(String numIids, String nick){
		TopResult res = new TopResult();
		try {
			TaobaokeItemsDetailGetRequest req = new TaobaokeItemsDetailGetRequest();
			req.setFields("click_url,shop_click_url,seller_credit_score,num_iid,title,cid,price");
			req.setNick(nick);
			req.setNumIids(numIids);
			TaobaokeItemsDetailGetResponse resp = client.execute(req);
			String errorCode = resp.getErrorCode();
			if (errorCode != null && !"".equals(errorCode)) {
				String errorStr = resp.getSubMsg();
				errorStr = errorStr != null ? errorStr : resp.getMsg();
				res.setErrorStr(errorStr);
			} else {
				if (resp.getTotalResults() != null && resp.getTotalResults().intValue() != 0) {
					for (TaobaokeItemDetail tbkid : resp.getTaobaokeItemDetails()) {
						// System.out.println(tbkid.getClickUrl());
						Item tbki = tbkid.getItem();
						TaobaokeItemsGetRequest req2 = new TaobaokeItemsGetRequest();
						req2.setFields("num_iid,click_url,shop_click_url,price,commission_rate,commission,volume");
						req2.setKeyword(tbki.getTitle());
						req2.setCid(tbki.getCid());
						req2.setStartPrice(tbki.getPrice());
						req2.setEndPrice(tbki.getPrice());
						req2.setPageNo(1L);
						req2.setPageSize(5L);
						TaobaokeItemsGetResponse resp2 = client.execute(req2);

						if (resp2.getTotalResults() != null && resp2.getTotalResults().intValue() != 0) {
							for (TaobaokeItem item : resp2.getTaobaokeItems()) {
								if (numIids.equals(item.getNumIid().toString())) {
									JSONObject result = new JSONObject();
									result.put("ori_price", item.getPrice());
									result.put("promo_price", item.getPrice());
									result.put("commission", item.getCommission());
									result.put("commission_rate", item.getCommissionRate());
									result.put("volume", item.getVolume());
									result.put("click_url", item.getClickUrl());
									result.put("err", "");

									UmpPromotionGetRequest umpPromotionGetRequest = new UmpPromotionGetRequest();
									umpPromotionGetRequest.setItemId(item.getNumIid());
									try {
										UmpPromotionGetResponse umpPromotionGetResponse = client
												.execute(umpPromotionGetRequest);
										List<PromotionInItem> promotionInItemList = umpPromotionGetResponse
												.getPromotions().getPromotionInItem();
										if (promotionInItemList.size() != 0) {
											PromotionInItem promotionInItem = promotionInItemList.get(0);
											result.put("promo_price", promotionInItem.getItemPromoPrice());
										}
									} catch (Exception e) {
										logger.error("something is wrong when call umpPromotionGetRequest :: ",e);
									}

									res.setResult(result.toString());
									break;
								}
							}
						} else {
							res.setErrorStr("没有找到该商品的推广..");
							break;
						}
					}
				} else {
					res.setErrorStr("没有找到该商品的推广.");
				}
			}

		} catch (ApiException e) {
			logger.error(e.toString());
			res.setErrorStr("运行时异常");
		}

		if (res.getErrorStr() == null && res.getResult() == null) {
			res.setErrorStr("没有找到该商品的推广...");
		}
		return res;
	}
	
//	public static void main(String[] args) throws Exception{
//		String res = TopApiUtil.tbkConvert("18173767841","karin婷").getJson();
//		System.out.println(res);
//	}
}
